package com.stu;

import java.util.concurrent.*;

/**
 * Created by chenhs on 2019/1/16.
 */
public class CountDownLatchTest {

    public static void main(String[] args) throws InterruptedException {
        // 初始化barrier 对应线程的个数
        CountDownLatch latch = new CountDownLatch(5);

        // 初始化线程池
        ExecutorService service = new ThreadPoolExecutor(10, 10,
                100000, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>());

        service.execute(new RunTaskTest(0, latch));
        service.execute(new RunTaskTest(1, latch));
        service.execute(new RunTaskTest(2, latch));
        service.execute(new RunTaskTest(3, latch));
        service.execute(new RunTaskTest(4, latch));

        latch.await(); // 主线程等待所有任务
        System.err.println("count down latch number " + latch.getCount());
        service.shutdown(); // 关闭线程池
    }

    static class RunTaskTest implements Runnable {
        int no; // number
        CountDownLatch latch;

        public RunTaskTest(int num, CountDownLatch latch) {
            this.no = num;
            this.latch = latch;
        }

        public void run() {
            // do some work
            System.err.println("NO. " + no + " is to count down");
            latch.countDown(); // 计数器 - 1
        }
    }

}
